package icu.shaoyayu.common.utll.encryption;

import icu.shaoyayu.common.utll.exception.CustomException;

import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * @author shaoyayu
 * @date 2021/12/22
 * @apiNote 哈希加密
 */
public class HashEncryption {

    /**
     * hash加密
     * @param encryptionString
     * @param hashEncryptedType
     * @return
     */
    public static String hashEncryption(String encryptionString, HashEncryptedType hashEncryptedType){
        try {
            MessageDigest md = MessageDigest.getInstance(hashEncryptedType.getName());
            md.update(encryptionString.getBytes("UTF-8"));
            byte[] result = md.digest();
            return new BigInteger(1, result).toString(16);
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException("encryption:"+e.getMessage());
        }
    }

    /**
     * 加盐加密
     * @param salt
     * @param encryptionString
     * @param hashEncryptedType
     * @return
     */
    private static String hashAddSaltEncryption(String salt, String encryptionString, HashEncryptedType hashEncryptedType){
        return hashEncryption(salt+encryptionString,hashEncryptedType);
    }

    public static void main(String[] args) {
        System.out.println(hashEncryption("hello123", HashEncryptedType.MD5));
    }

}
